407B - Long Path - CodeForces Solution


dp implementation *1600

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#include <algorithm>


#define yes cout<<"YES"<<endl
#define no cout<<"NO"<<endl
 
typedef long long int ll;
using namespace std;
 
 
ll mydiv(ll a, ll b){
    if( a % b == 0)
        return a / b;
    else
        return (a / b) + 1;
}
 
long long gcd(long long int a, long long int b)
{
  if (b == 0)
    return a;
  return gcd(b, a % b);
}
 
// Function to return LCM of two numbers
long long lcm(ll a, ll b)
{
    return (a / gcd(a, b)) * b;
}

void solve(){
    
    ll n, m = 1000000007;
    cin>>n;
    
    vector <ll> v(n + 1), dp(n + 1);
    
    for(ll i = 1; i <= n; i++)
        cin>>v[i];
    
    dp[0] = 0;
    
    for(ll i = 1; i <= n; i++){
        if(v[i] == i)
            dp[i] = (dp[i - 1] + 2) % m;
        else{
            if(dp[i - 1] <= dp[v[i] - 1])
                dp[i] = ((dp[i - 1] + 2) % m + (m + dp[i - 1] - dp[v[i] - 1]) % m) % m;
            else
                dp[i] = ((dp[i - 1] + 2) % m + (dp[i - 1] - dp[v[i] - 1]) % m) % m;
        }
    }
    cout<<dp[n];
}

int main(){
    
    ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
    solve();
	
	return 0;
}


Comments

Submit
0 Comments
More Questions

938A - Word Correction
159C - String Manipulation 10
258A - Little Elephant and Bits
1536C - Diluc and Kaeya
1428C - ABBB
1557A - Ezzat and Two Subsequences
255A - Greg's Workout
1059A - Cashier
1389C - Good String
1561A - Simply Strange Sort
1337B - Kana and Dragon Quest game
137C - History
1443C - The Delivery Dilemma
6C - Alice Bob and Chocolate
1077C - Good Array
285B - Find Marble
6A - Triangle
1729A - Two Elevators
1729B - Decode String
1729C - Jumping on Tiles
1729E - Guess the Cycle Size
553B - Kyoya and Permutation
1729D - Friends and the Restaurant
1606C - Banknotes
580C - Kefa and Park
342A - Xenia and Divisors
1033A - King Escape
39D - Cubical Planet
1453A - Cancel the Trains
645A - Amity Assessment